package com.beijiteshop.shop.ui.category.vm

import androidx.lifecycle.MutableLiveData
import com.beijiteshop.libcommon.base.viewmodel.BaseViewModel
import com.beijiteshop.libcommon.network.ext.onBizEmpty
import com.beijiteshop.libcommon.network.ext.onBizError
import com.beijiteshop.libcommon.network.ext.onBizOK
import com.beijiteshop.libcommon.network.ext.serverData
import com.beijiteshop.libcommon.network.model.onFailure
import com.beijiteshop.libcommon.network.model.onSuccess
import com.beijiteshop.shop.model.api.response.CategoryBean
import com.beijiteshop.shop.model.entity.ProductItemEntity
import com.beijiteshop.shop.ui.category.repo.CategoryRepo

/**
 * @Author LiaoZhongKai
 * @Date 2021/3/10 19:26
 * @Description
 */
class CategoryVM(private val repo: CategoryRepo) : BaseViewModel() {

    val liveCategories = MutableLiveData<List<CategoryBean>>()
    val liveCategoryProducts = MutableLiveData<MutableList<ProductItemEntity>>()

    fun getCategories() = launch {
        repo.getCategories()
            .serverData()
            .onSuccess {
                onBizOK { code, data, message ->
                    liveCategories.postValue(data)
                }

                onBizError { code, message ->
                    liveError.postValue(message)
                }
            }
            .onFailure {
                liveNetError.postValue(it.message)
            }
    }

    fun getCategoryProducts(page: Int,typeId: String) = launch {
        repo.getCategoryProducts(page, typeId)
            .serverData()
            .onSuccess {
                onBizOK { code, data, message ->
                    if (data.isNullOrEmpty()){
                        liveEmpty.postValue(null)
                    }else{
                        val result = mutableListOf<ProductItemEntity>()
                        data.forEach {
                            result.add(ProductItemEntity(ProductItemEntity.TYPE_COMMON_GOODS,1,it))
                        }
                        liveCategoryProducts.postValue(result)
                    }
                }

                onBizError { code, message ->
                    liveError.postValue(message)
                }

                onBizEmpty {
                    liveEmpty.postValue(it)
                }
            }
            .onFailure {
                liveNetError.postValue(it.message)
            }
    }
}